<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>交易走势图 - 近七日交易走势</span>
        <el-radio-group v-model="formData.type" @change="handleChangeType">
          <el-radio-button label="1">普通订单</el-radio-button>
          <el-radio-button label="2">积分订单</el-radio-button>
        </el-radio-group>
      </div>
    </template>

    <div v-loading="isLoading">
      <ChartLine
        v-if="!isLoading"
        :xAxisData="xAxisData"
        :legendData="legendData"
        :series="series"
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import ChartLine from '@/components/ChartLine.vue';
import { actionStatModule } from '@/apis/stat';

// 加载状态(默认true)
const isLoading = ref(true);

interface OrderTrend {
  day: string;
  trade: number;
  deal: number;
  tradeCount: number;
  dealCount: number;
}

interface ChartLegendData {
  label: string;
  field: keyof OrderTrend;
}

const tempList: ChartLegendData[] = [
  {
    label: '交易额',
    field: 'trade'
  },
  {
    label: '成交额',
    field: 'deal'
  },
  {
    label: '交易量',
    field: 'tradeCount'
  },
  {
    label: '成交量',
    field: 'dealCount'
  }
];

const xAxisData = ref();
const legendData = ref();
const series = ref();

const endTime = Date.now();
const startTime = endTime - 7 * 86400000;
const formData = reactive({
  type: '1'
});

const handleChangeType = () => {
  requestData();
};

const requestData = () => {
  const dataOpt = {
    startTime,
    endTime,
    ...formData
  };

  isLoading.value = true;
  actionStatModule<OrderTrend[]>('statOrderByTrend', dataOpt).then((res) => {
    // 提取数据 - xAxis.data
    xAxisData.value = res.data.map((item) => item.day);
    // 提取数据 - legend.data
    legendData.value = tempList.map((item) => item.label);
    // 提取数据 - series
    series.value = tempList.map((item) => ({
      name: item.label,
      type: 'line',
      data: res.data.map((_item) => _item[item.field])
    }));

    isLoading.value = false;
  });
};

onMounted(() => {
  requestData();
});
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
